package service

import (
	"errors"
	"fitness/go-admin/internal/model"
	"fitness/go-admin/internal/repository"
	"time"
)

type MemberService interface {
	Create(req *model.MemberCreateReq) error
	Update(id uint, req *model.MemberUpdateReq) error
	Delete(id uint) error
	GetByID(id uint) (*model.Member, error)
	List(page, pageSize int) ([]model.Member, int64, error)
}

type memberService struct {
	repo repository.MemberRepository
}

func NewMemberService(repo repository.MemberRepository) MemberService {
	return &memberService{repo: repo}
}

func (s *memberService) Create(req *model.MemberCreateReq) error {
	// 检查手机号是否已存在
	if existing, _ := s.repo.GetByPhone(req.Phone); existing != nil {
		return errors.New("手机号已存在")
	}

	member := &model.Member{
		Name:       req.Name,
		Phone:      req.Phone,
		Email:      req.Email,
		Gender:     req.Gender,
		MemberType: req.MemberType,
		Status:     1,
	}

	// 解析日期
	if req.Birthday != "" {
		if t, err := time.Parse("2006-01-02", req.Birthday); err == nil {
			member.Birthday = t
		}
	}
	if req.ExpireDate != "" {
		if t, err := time.Parse("2006-01-02", req.ExpireDate); err == nil {
			member.ExpireDate = t
		}
	}

	return s.repo.Create(member)
}

func (s *memberService) Update(id uint, req *model.MemberUpdateReq) error {
	member, err := s.repo.GetByID(id)
	if err != nil {
		return errors.New("会员不存在")
	}

	if req.Name != "" {
		member.Name = req.Name
	}
	if req.Email != "" {
		member.Email = req.Email
	}
	if req.Gender != "" {
		member.Gender = req.Gender
	}
	if req.MemberType != "" {
		member.MemberType = req.MemberType
	}
	if req.Status != nil {
		member.Status = *req.Status
	}
	if req.Birthday != "" {
		if t, err := time.Parse("2006-01-02", req.Birthday); err == nil {
			member.Birthday = t
		}
	}
	if req.ExpireDate != "" {
		if t, err := time.Parse("2006-01-02", req.ExpireDate); err == nil {
			member.ExpireDate = t
		}
	}

	return s.repo.Update(member)
}

func (s *memberService) Delete(id uint) error {
	if _, err := s.repo.GetByID(id); err != nil {
		return errors.New("会员不存在")
	}
	return s.repo.Delete(id)
}

func (s *memberService) GetByID(id uint) (*model.Member, error) {
	return s.repo.GetByID(id)
}

func (s *memberService) List(page, pageSize int) ([]model.Member, int64, error) {
	if page < 1 {
		page = 1
	}
	if pageSize < 1 || pageSize > 100 {
		pageSize = 10
	}
	return s.repo.List(page, pageSize)
}
